<template>
  <!-- 返工通知配置表单弹窗 -->
  <el-dialog
    v-model="visibleDialog"
    :title="props.title"
    width="50%"
    draggable
    @close="closeDialog"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="160">
      <el-row>
        <el-col :span="11">
          <el-form-item label="设备编码" prop="equipCode">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.equipCode"
              placeholder="请选择设备"
              clearable
              readonly
              style="width: 100%"
              @click="openSelectDialog"
            >
              <template #append>
                <el-button type="success" plain @click="openSelectDialog"
                  >选择</el-button
                >
              </template>
            </el-input>
            <span v-else>{{ formData.equipCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="产品" prop="productId">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.productCode"
              placeholder="请选择成品物料"
              clearable
              readonly
              style="width: 100%"
              @click="showWorkOrderSelect"
            >
              <template #append>
                <el-button type="success" plain @click="showWorkOrderSelect"
                  >选择</el-button
                >
              </template>
            </el-input>
            <span v-else>{{ formData.productCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="返工通知人员姓名" prop="userName">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.userName"
              placeholder="请输入返工通知人员姓名"
              clearable
            />

            <span v-else>{{ formData.userName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="返工通知邮箱" prop="email">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.email"
              placeholder="请输入返工通知邮箱"
              clearable
            />

            <span v-else>{{ formData.email }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="返工通知分类" prop="category">
            <el-select
              style="width: 100%"
              v-if="!props.isReadonly"
              v-model="formData.category"
              placeholder="请选择返工通知分类"
              clearable
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList('NoticeTypes')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>

            <span v-else>{{
              dictionaryStore.filterDictName("NoticeTypes", formData.category)
            }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
  <product-select
    :visible="productDialogSelect.visible"
    @change-visible="changeProductVisible"
    :plantId="formData.plantId"
    :materialType="3"
    :backList="productBackList"
  />
  <SelectDeviceDialog-Eam
    v-model:visible="selectDialog.visible"
    :data="selectDialog.data"
    :isMultiple="false"
    @echo-info="changeVisible"
  />
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "QMSROKNOTICEEMAILADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  equipCode: [
    { required: true, message: "请选择设备", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  productId: [
    { required: true, message: "请选择产品", trigger: "blur" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  productCode: [
    { required: true, message: "请选择产品", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  userName: [
    // { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  email: [
    // { required: true, message: "请输入邮箱", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  category: [
    // { required: true, message: "请选择分类", trigger: "blur" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  deleted: [],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  equipId: "",
  equipCode: "",
  equipName: "",
  productId: "",
  productCode: "",
  productName: "",
  userName: "",
  email: "",
  category: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        equipId,
        equipCode,
        equipName,
        productId,
        productCode,
        productName,
        userName,
        email,
        category,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      } = newVal;
      Object.assign(formData, {
        id,
        equipId,
        equipCode,
        equipName,
        productId,
        productCode,
        productName,
        userName,
        email,
        category,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      });
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.equipId = "";
  formData.equipCode = "";
  formData.equipName = "";
  formData.productId = "";
  formData.productCode = "";
  formData.productName = "";
  formData.userName = "";
  formData.email = "";
  formData.category = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
}
//设备显隐
const selectDialog = reactive<DialogOption>({
  visible: false,
  data: [],
});
//  点击设备
function openSelectDialog() {
  selectDialog.visible = true;
  selectDialog.data = formData.equipId
    ? [
        {
          id: formData.equipId,
          assetName: formData.equipName,
          assetCode: formData.equipCode,
        },
      ]
    : [];
}
// 设备选择确认后的回调函数
const changeVisible = (options: any) => {
  if (options && options.length) {
    const data = options[0];
    formData.equipId = data.id;
    formData.equipCode = data.assetCode;
    formData.equipName = data.assetName;
  } else {
    formData.equipId = "";
    formData.equipCode = "";
    formData.equipName = "";
  }
};
const loading = ref(false);
//选择成品弹窗
const productDialogSelect = ref({
  visible: false,
});
const changeProductVisible = (val: boolean, data: any) => {
  productDialogSelect.value.visible = val;
  if (data) {
    formData.productId = data.id;
    formData.productName = data.materialName;
    formData.productCode = data.materialCode;
  }
};
// 回显的数据
const productBackList = ref([]);
const showWorkOrderSelect = () => {
  productDialogSelect.value.visible = true;
};
/** 返工通知配置保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/qms/roknoticeemail/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
